package com.hk.core.authentication.security.authentication.accesstoken;

import com.hk.commons.util.ArrayUtils;
import com.hk.commons.util.StringUtils;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.web.util.matcher.RequestMatcher;

import java.util.Arrays;

public record TokenRequestMatcher(String header, String tokenParameter, String cookieName) implements RequestMatcher {

    @Override
    public boolean matches(HttpServletRequest request) {
        String token = tokenResolve(request);
        return StringUtils.hasLength(token);
    }

    private String resolveTokenFormCookie(HttpServletRequest request) {
        if (!StringUtils.hasLength(cookieName)) {
            return null;
        }
        Cookie[] cookies = request.getCookies();
        return ArrayUtils.isEmpty(cookies) ? null : Arrays.stream(cookies)
                .filter(item -> StringUtils.equals(cookieName, item.getName()))
                .findFirst()
                .map(Cookie::getValue)
                .orElse(null);
    }

    public String tokenResolve(HttpServletRequest request) {
        String token = StringUtils.hasLength(header) ? request.getHeader(header) : null;
        if (!StringUtils.hasLength(token) && StringUtils.hasLength(tokenParameter)) {
            token = request.getParameter(tokenParameter);
        }
        if (!StringUtils.hasLength(token)) {
            token = resolveTokenFormCookie(request);
        }
        return token;
    }
}
